<?php
namespace Api\Controller;

use Api\Controller\CommonController;
use Think\Log;
class TaskController extends CommonController
{
    /*任务模块*/

    public function getTask()
    {
        $_validate = array(
            array('carid', '用户不存在')
        );
        if (!$this->validate($_validate)) {
            $this->errorReturn($this->getError());
        }
        $data = $this->getData();
        $where = 't.car_id=' . $data['carid'] . ' and t.status=1';
        if($data['task_id']>0){
            $where = 't.car_id=' . $data['carid'] . ' and  t.id ='.$data['task_id'];
        }
        //获取任务
        $taskdb = M('Task');
        $taskdb->where('status=1 and public_time<'.(time()-180))->save(array('status'=>3,'note'=>'三分钟未处理,自动放弃任务'));
        $task = $taskdb->table("__TASK__ t")->field('t.id,t.site_id,t.task_from,t.task_from_longitude,t.task_from_mobile,t.task_from_latitude,t.task_end,
        t.task_end_longitude,t.task_end_latitude,t.mobile as task_end_mobile,t.car_id,t.status,t.step,t.car_load,t.total_load,t.load_site,t.unload_type,
        t.public_time,t.grade,t.components,rd.point,rd.distance,rd.duration')
            ->join("LEFT JOIN __ROADS_DETAIL__ as rd on t.roads_id=rd.roads_id")->where($where)->find();
        if (empty($task)) {
            $this->successReturn('操作成功', array('task' => ''));
        }
        $this->successReturn('操作成功', array('task' => $task));
    }

    public function taskDismiss()
    {
        $_validate = array(
            array('carId', '车辆ID必须填写'),
            array('taskId', '任务必须填写')
        );
        if (!$this->validate($_validate)) {
            $this->errorReturn($this->getError());
        }
        $data = $this->getData();
        $taskdb = M('Task');
        $taskdb->where('car_id=' . $data['carId'] . ' and id=' . $data['taskId'])->save(array('status' => 3, 'note' => '用户主动放弃'));
        $this->successReturn('操作成功');
    }
    
    /*拒绝任务*/
    public function  refuse_task(){
        $task_id=I('post.id');
        $user_id=I('post.user_id');
        $ansytask=M('ansytask');
        $arr=$ansytask->alias('a')->join('__TASK__ b ON a.task_id = b.id')->field('b.task_end,b.car_no')->where(['a.id'=>$task_id])->find();
        $data=[
            'uid'=>$user_id,
            'gongdi'=>$arr['task_end'],
            'is_num'=>$arr['car_no'],
            'addtime'=>date('Y-m-d H:i:s')
        ];
        M('refuse_log')->add($data);
        /*这里还需要调用短信接口并且*/
    }
    
    /*接任务*/
    public function taskStart()
    {
        $_validate = array(
            array('carId', '车辆ID必须填写'),
            array('taskId', '任务必须填写')
        );
        if (!$this->validate($_validate)) {
            $this->errorReturn($this->getError());
        }
        $data = $this->getData();
        $taskdb = M('Task');
        $task = $taskdb->where('car_id=' . $data['carId'] . ' and id=' . $data['taskId'])->find();
        if($task['status']!=1){
            $this->successReturn('操作成功',array('res'=>0,'msg'=>'任务已经取消'));
        }
        $taskdb->where('car_id=' . $data['carId'] . ' and id=' . $data['taskId'])->save(array('status' => 2, 'step' => 1));
        //添加任务执行日志
        $task_logdb = M('Task_log');
        $task_logdb->where(array('task_id' => $data['taskId'], 'car_id' => $data['carId']))->save(array('start_time' => time()));
        $this->successReturn('操作成功',array('res'=>1,'msg'=>'开始执行'));
    }
    
    /*接任务*/
    public function taskStartLoad()
    {
        $_validate = array(
            array('carId', '车辆ID必须填写'),
            array('taskId', '任务必须填写')
        );
        if (!$this->validate($_validate)) {
            $this->errorReturn($this->getError());
        }
        $data = $this->getData();
        $taskdb = M('Task');
        $task = $taskdb->where('car_id=' . $data['carId'] . ' and id=' . $data['taskId'])->find();
        if($task['status']==3){
            $this->successReturn('操作成功',array('res'=>0,'msg'=>'任务已经取消'));
        }
        $taskdb->where('car_id=' . $data['carId'] . ' and id=' . $data['taskId'])->save(array('step' => 2));
        //添加任务执行日志
        $task_logdb = M('Task_log');
        $task_logdb->where(array('task_id' => $data['taskId'], 'car_id' => $data['carId']))->save(array('load_time' => time()));
        $this->successReturn('操作成功',array('res'=>1,'msg'=>'开始执行'));
    }
    /*停车5分钟记录*/
    public  function  stop_log(){
        $task_id=I('post.task_id');
        $stop_time=I('post.stop_time');
        $arr=M('task')->where(['id'=>$task_id])->field('task_from,task_end,car_id')->find();
        $data=[
            'task_id'=>$task_id,
            'task_torm'=>$arr['task_from'],
            'task_end'=>$arr['task_end'],
            'stop_time'=>$stop_time,
            'addtime'=>date('Y-m-d H:i:s'),
            'user_id'=>$arr['car_id']
        ];
        M('stop_log')->add($data);
    }
    
    /*短信提醒*/
    public  function  remind_sms(){
    
    }
    
    /**
     * 发车 即装料完成
     */
    public function taskDeparture()
    {
        $_validate = array(
            array('carId', '车辆ID必须填写'),
            array('taskId', '任务必须填写')
        );
        if (!$this->validate($_validate)) {
            $this->errorReturn($this->getError());
        }
        $data = $this->getData();
        $taskdb = M('Task');
        $task = $taskdb->where('car_id=' . $data['carId'] . ' and id=' . $data['taskId'])->find();
        if($task['status']==3){
            $this->successReturn('操作成功',array('res'=>0,'msg'=>'任务已经取消'));
        }
        $taskdb->where('car_id=' . $data['carId'] . ' and id=' . $data['taskId'])->save(array('step' => 3));
        //添加任务执行日志
        $task_logdb = M('Task_log');
        $task_logdb->where(array('task_id' => $data['taskId'], 'car_id' => $data['carId']))->save(array('depature_time' => time()));
        $this->successReturn('操作成功',array('res'=>1,'msg'=>'开始执行'));
    }
    /**
     * 抵达站点并开始卸料
     */
    public function taskUnload()
    {
        $_validate = array(
            array('carId', '车辆ID必须填写'),
            array('taskId', '任务必须填写')
        );
        if (!$this->validate($_validate)) {
            $this->errorReturn($this->getError());
        }
        $data = $this->getData();
        $taskdb = M('Task');
        $task = $taskdb->where('car_id=' . $data['carId'] . ' and id=' . $data['taskId'])->find();
        if($task['status']==3){
            $this->successReturn('操作成功',array('res'=>0,'msg'=>'任务已经取消'));
        }
        $taskdb->where('car_id=' . $data['carId'] . ' and id=' . $data['taskId'])->save(array('step' => 4));
        //添加任务执行日志
        $task_logdb = M('Task_log');
        $task_logdb->where(array('task_id' => $data['taskId'], 'car_id' => $data['carId']))->save(array('arrived_time' => time(),'unloading_time' => time()));
        $this->successReturn('操作成功',array('res'=>1,'msg'=>'开始执行'));
    }

    /**
     * 卸料完成
     */
    public function taskFinish()
    {
        $_validate = array(
            array('carId', '车辆ID必须填写'),
            array('taskId', '任务必须填写')
        );
        if (!$this->validate($_validate)) {
            $this->errorReturn($this->getError());
        }
        $data = $this->getData();

//        $task =   $taskdb->where('car_id=' . $data['carId'] . ' and id=' . $data['taskId'])->find();
        //添加任务执行日志
        $task_logdb = M('Task_log');
        $task_logdb->where(array('task_id' => $data['taskId'], 'car_id' => $data['carId']))->save(array('unload_finish_time' => time()));

//        //添加记录
//        $month = strtotime(date('Y-m-01'));
//        $dbcount = M('Task_count');
//        $countDate = $dbcount->where(array('month'=>$month,'car_id'=> $data['carId']))->find();
//        $tadiao = $task['unload_type']==1?1:0;

        $taskdb = M('Task');
        $task = $taskdb->where('car_id=' . $data['carId'] . ' and id=' . $data['taskId'])->find();
        if($task['status']==3){
            $this->successReturn('操作成功',array('res'=>0,'msg'=>'任务已经取消'));
        }
        $taskdb->where('car_id=' . $data['carId'] . ' and id=' . $data['taskId'])->save(array('step' => 5));
//        if(!empty($countDate)){
//            $tadiao+=$countDate['tadiao'];
//            $dbcount->where('id='.$countDate['id'])->save(array('tadiao'=>$tadiao,'number'=>1,'number'=>$countDate['number']+1,'totaltime'=>$countDate['totaltime']+$usetime));
//        }else{
//            $tadiao = $task['unload_type']==1?1:0;
//            $dbcount->add(array('month'=>$month,'car_id'=> $data['carId'],'tadiao'=>$tadiao,'number'=>1,'totaltime'=>$usetime));
//        }

        $this->successReturn('操作成功',array('res'=>1,'msg'=>'开始执行'));
    }


    public function taskGoback()
    {
        $_validate = array(
            array('carId', '车辆ID必须填写'),
            array('taskId', '任务必须填写')
        );
        if (!$this->validate($_validate)) {
            $this->errorReturn($this->getError());
        }
        $data = $this->getData();
        //添加任务执行日志
        $task_logdb = M('Task_log');
        $task_logdb->where(array('task_id' => $data['taskId'], 'car_id' => $data['carId']))->save(array('return_time' => time()));
        $this->successReturn('操作成功');
    }

    /**
     * 返回到站点,任务完成
     */
    public function taskEnd()
    {
        $_validate = array(
            array('carId', '车辆ID必须填写'),
            array('taskId', '任务必须填写')
        );
        if (!$this->validate($_validate)) {
            $this->errorReturn($this->getError());
        }
        $data = $this->getData();
        $taskdb = M('Task');
        $task = $taskdb->where('car_id=' . $data['carId'] . ' and id=' . $data['taskId'])->find();
        if($task['status']==3){
            $this->successReturn('操作成功',array('res'=>0,'msg'=>'任务已经取消'));
        }
        //添加任务执行日志
        $task_logdb = M('Task_log');
        $task_logdb->where(array('task_id' => $data['taskId'], 'car_id' => $data['carId']))->save(array('finish_time' => time()));
        $tas_log =  $task_logdb->where(array('task_id' => $data['taskId'], 'car_id' => $data['carId']))->find();
        $use_time = floor((time()-$tas_log['load_time'])/60);
        $taskdb->where('car_id=' . $data['carId'] . ' and id=' . $data['taskId'])->save(array('step' => 7,'use_time'=>$use_time,'finish_time'=>time(), 'status' => 4));
        $this->successReturn('操作成功',array('res'=>1,'msg'=>'开始执行'));
    }

    public function taskList()
    {
        $_validate = array(
            array('carId', '车辆ID必须填写'),
            array('status', '类型必须填写')
        );
        if (!$this->validate($_validate)) {
            $this->errorReturn($this->getError());
        }
        $data = $this->getData();
        $taskdb = M('Task');
//        $taskdb->where('status=1 and public_time<'.(time()-180))->save(array('status'=>3,'note'=>'三分钟未处理,自动放弃任务'));


        $page = $data['page'] ? $data['page'] : 1;
        $pagesize = $data['pagesize'] ? $data['pagesize'] : 5;
        $limit = ($page - 1) * $pagesize . "," . $pagesize;
        $where = 't.car_id=' . $data['carId'] . ' and t.status=' . $data['status'];
        $datatype = $data['datatype'];
        if($datatype==2){
            $p1=this_monday();
            $p2=this_sunday();
            $where.=' and t.public_time>='.$p1.' and t.public_time<='.$p2;
        }
        if($datatype==3){
            $p1=month_firstday();
            $p2=month_lastday();
            $where.=' and t.public_time>='.$p1.' and t.public_time<='.$p2;
        }
        if($datatype==4){
            $p1=strtotime(date('Y').'-01-01 00:00:00');
            $p2=strtotime(date('Y').'-12-31 23:59:59');
            $where.=' and t.public_time>='.$p1.' and t.public_time<='.$p2;
        }
        $dbdata = $taskdb->table("__TASK__ t")->field('t.id,t.orderno,t.site_id,t.task_from,t.task_from_longitude,t.task_from_mobile,t.task_from_latitude,t.task_end,
       t.distance, t.task_end_longitude,t.task_end_latitude,t.mobile as task_end_mobile,t.car_id,t.status,t.step,t.car_load,t.total_load,t.load_site,t.unload_type,
       t.public_time,t.grade,t.components,log.arrived_time,log.depature_time,rd.point,rd.duration')
            ->join("LEFT JOIN __ROADS_DETAIL__ as rd on t.roads_id=rd.roads_id")
            ->join("LEFT JOIN __TASK_LOG__ as log on log.task_id=t.id")
            ->where($where)
            ->limit($limit)
            ->order('t.public_time desc')
            ->select();
        Log::write($taskdb->getLastSql());
        $this->successReturn('获取订单成功', $dbdata);

    }

    public function taskCount(){
        $_validate = array(
            array('carId', '用户不存在')
        );
        if (!$this->validate($_validate)) {
            $this->errorReturn($this->getError());
        }
        $data = $this->getData();
        $beginDate = strtotime(date('Y-m').'-01 00:00:00');
        $endDate = strtotime(date('Y-m').'-01 23:59:59 +1 month -1 day');
        $where =' t.public_time>='.$beginDate.' and t.public_time<='.$endDate .' and car_id ='.$data['carId'] .' and status=4';
        $taskdb = M('Task');
        $dbdata = $taskdb->table("__TASK__ t")->field('sum(distance) total_dis,sum(use_time) total_time')->where($where)->group('car_id')->find();
        $this->successReturn('获取订单成功', $dbdata);

    }
}